package com.djzhu.component.mapreduce;

import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;

public class WordCount {

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
        if (otherArgs.length < 2) {
            System.err.println("Usage: wordcount <in> [<in>...] <out>");
            System.exit(2);
        }
        Job job = Job.getInstance(conf, "word count");
        job.setJarByClass(WordCount.class);
        /**mapreduce的主要流程*/

        /**map阶段*/
        //1. 输入文件, 输出key1, value1
        for (int i = 0; i < otherArgs.length - 1; ++i) {
            FileInputFormat.addInputPath(job, new Path(otherArgs[i]));
        }
        //2. 对key1, value1进行map得到key2, value2
        job.setMapperClass(TokenizerMapper.class);

        /**shuffle阶段*/
        //3. 对map阶段发出的key-value进行分区
//        job.setPartitionerClass();
        //4. 对分区之后的数据在分区内部进行排序
//        job.setSortComparatorClass();
        //5. 分组后的数据进行规约(combine操作)，降低数据的网络拷贝（可选步骤).
        //   比如在wordCount的例子中,因为同个分区内的数据都是相同的key,
        //   我们可以先对其进行计数, 最后将分区内部规约化的总数传给下一步.
        //   缺少此步骤的时候会将所有的key-value(value均为1)都传给下一步.
        job.setCombinerClass(IntSumReducer.class);


        /**reduce阶段*/
        //6. 接受shuffle传进来的key-value, 排序, 做reduce操作
        job.setReducerClass(IntSumReducer.class);
        job.setNumReduceTasks(4);   //指定reduce数量

        //7. 输出文件
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        FileOutputFormat.setOutputPath(job,
                new Path(otherArgs[otherArgs.length - 1]));
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }

    public static class TokenizerMapper
            extends Mapper<Object, Text, Text, IntWritable>{

        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();

        public void map(Object key, Text value, Context context
        ) throws IOException, InterruptedException {
            StringTokenizer itr = new StringTokenizer(value.toString());
            while (itr.hasMoreTokens()) {
                word.set(itr.nextToken());
                context.write(word, one);
            }
        }
    }

    public static class IntSumReducer
            extends Reducer<Text,IntWritable,Text,IntWritable> {
        private IntWritable result = new IntWritable();

        public void reduce(Text key, Iterable<IntWritable> values,
                           Context context
        ) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable val : values) {
                sum += val.get();
            }
            result.set(sum);
            context.write(key, result);
        }
    }
}
